import os
from time import sleep

from config import constants
from lib.adb_ import is_app_focus
from lib.image_ import is_image_match
from submodules.common.lib import os_, local_paths
from submodules.common.lib.log_ import get_logger
from workspace.workspace_lib import 启动APP并登录账号

project_tmp_path = local_paths.project_tmp_path

tmp_images_dir = os.path.join(project_tmp_path, "tmp_images")

logger = get_logger()
is_not_focus_count = 0

while True:
    # 在app但是长时间未变化（卡死）的场景
    file_list = os.listdir(tmp_images_dir)
    file_list.sort(reverse=True)
    is_screenshot_compare_count = 0
    is_screenshot_same_count = 0
    file_path_tmp = None
    for file_name in file_list:
        sleep(2)
        logger.info(f"is_not_focus_count:{is_not_focus_count}")
        logger.info(f"is_screenshot_same_count:{is_screenshot_same_count}")
        # 离开app的场景
        res = is_app_focus(constants.PACKAGE_NAME_WENDAO)
        if not res:
            is_not_focus_count += 1
        else:
            is_not_focus_count = 0
        if is_not_focus_count > 15:
            is_not_focus_count = 0
            启动APP并登录账号(1)
            break

        if "screenshot" in file_name:
            file_path = os.path.join(tmp_images_dir, file_name)
            if file_path_tmp is None:
                file_path_tmp = file_path
            else:
                is_screenshot_compare_count += 1
                res = is_image_match(file_path, file_path_tmp)
                if res:
                    is_screenshot_same_count += 1
                else:
                    break
                if is_screenshot_same_count >= 15:
                    is_not_focus_count = 0
                    启动APP并登录账号(1)
                    break
                if is_screenshot_compare_count > 15:
                    break
